package com.jiezuo.auth.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.jiezuo.auth.entity.Depart;
import com.jiezuo.auth.service.DepartService;
import com.jiezuo.common.annotation.RepeatSubmit;
import com.jiezuo.common.base.BaseController;
import com.jiezuo.common.enums.ResultEnums;
import com.jiezuo.common.exception.BusinessRuntimeException;
import com.jiezuo.common.util.*;
import com.jiezuo.common.vo.PageVo;
import com.jiezuo.common.vo.Result;
import lombok.extern.slf4j.Slf4j;
import org.flowable.common.engine.impl.util.CollectionUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * @description 部门信息
 * @author 王帅
 * @date 2020/08/04 16:56
 * @version V1.0
 **/
@Slf4j
@Transactional
@RequestMapping("/depart")
@RestController
//部门信息", tags = {"部门信息接口"})
public class DepartController extends BaseController {

    @Autowired
    private DepartService departService;

    //查询带分页列表", notes = "查询带分页列表")
    @GetMapping("/findPage")
    public Result<IPage<Depart>> findPage(@ModelAttribute PageVo pageVo, @ModelAttribute Depart depart) {
        IPage<Depart> page = departService.findPage(pageVo, depart);
        return new ResultUtil<IPage<Depart>>().setData(page);
    }

    //查询不带分页列表", notes = "查询不带分页列表")
    @GetMapping("/findList")
    public Result<List<Depart>> findList(@ModelAttribute Depart depart) {
        List<Depart> list = departService.findList(depart);
        return new ResultUtil<List<Depart>>().setData(list);
    }

    //(委托)查询统计--个人汇总", notes = "(委托)查询统计--个人汇总")
    @GetMapping("/findGather")
    public Result<List<Depart>> findGather() {
        List<Depart> list = departService.findGather();
        return new ResultUtil<List<Depart>>().setData(list);
    }

    //通过ID查询", notes = "通过ID查询")
    @GetMapping("/findById")
    public Result<Depart> findById(String id) {
        Depart depart = departService.getById(id);

        // 只是为了，供前端使用  无意义
        depart.setLabel(depart.getName());

        return new ResultUtil<Depart>().setData(depart);
    }

    @RepeatSubmit
    //添加", notes = "添加")
    @PostMapping("/save")
    public Result save(@RequestBody Depart depart) {
        departService.saveDepart(depart);
        return new ResultUtil().setSuccessMsg(ResultEnums.OK.getReasonPhraseCN());
    }

    //修改", notes = "修改")
    @PostMapping("/update")
    public Result update(@RequestBody Depart depart) {
        VerifyUtil.notEmpty("部门主键", depart.getId());
        VerifyUtil.notEmpty("上级部门", depart.getPid());
        VerifyUtil.notEmpty("是否检测部门", depart.getIs_branch());
        VerifyUtil.notEmpty("所属企业", depart.getAffiliation_enterprise());
        VerifyUtil.notEmpty("部门编码",depart.getCode());
        List<Depart> list = departService.list();
        String ids = "";
        //自己的父id不能与自己相同
        if (depart.getId().equals(depart.getPid())) {
            return new ResultUtil().setErrorMsg("上级部门不能选择自己");
        }
        //所有子级ID
        String allChildrenIds = allChildren(list, ids, depart.getId());
        String[] arr = allChildrenIds.split(",");
        //自己不能添加到自己的子级
        if (Arrays.asList(arr).contains(depart.getPid())) {
            return new ResultUtil().setErrorMsg("上级部门不能选择自己的子级部门");
        }
        if ("0".equals(depart.getPid())) {
            depart.setAncestors(depart.getPid() + "," + depart.getId());
        } else {
            Depart d = departService.getById(depart.getPid());
            depart.setAncestors(d.getAncestors() + "," + depart.getId());
            if (!d.getAffiliation_enterprise().equals(depart.getAffiliation_enterprise())) {
                throw new BusinessRuntimeException("当前部门所属企业与上级部门所属企业不一致，请确认上级部门是否需要变更");
            }
        }
        QueryWrapper<Depart> departQueryWrapper = new QueryWrapper<>();
        departQueryWrapper.eq("code",depart.getCode());
        departQueryWrapper.ne("id",depart.getId());
        departQueryWrapper.eq("is_delete","0");
        List<Depart> departList = departService.list(departQueryWrapper);
        if(!CollectionUtil.isEmpty(departList)){
            throw new BusinessRuntimeException("该部门编码【"+depart.getCode()+"】已存在,请修改");
        }
        if(!StringUtil.isNotEmpty(depart.getMain_leader())){depart.setMain_leader(null);}//部门主管领导:可以为空
//        departService.updateById(depart);
        departService.updateDepart(depart);
        // 自己有子级，也需要处理
        QueryWrapper<Depart> childrenQueryWrapper = new QueryWrapper<>();
        childrenQueryWrapper.eq("pid", depart.getId());
        childrenQueryWrapper.eq("is_delete", "0");
        List<Depart> childrenList = departService.list(childrenQueryWrapper);
        if (childrenList.size() > 0) {
            for (Depart child : childrenList) {
                child.setAncestors(depart.getPid() + "," + depart.getId() + "," + child.getId());
                child.setAffiliation_enterprise(depart.getAffiliation_enterprise());
            }
            departService.updateBatchById(childrenList);
        }
        return new ResultUtil().setSuccessMsg(ResultEnums.OK.getReasonPhraseCN());
    }


    //查询所有子级的父ID
    public String allChildren(List<Depart> list, String ids, String id) {
        if (isNotChildren(list, id)) {
            for (Depart depart : list) {
                if (id.equals(depart.getPid())) {
                    ids = allChildren(list, ids, depart.getId());
                    ids += depart.getId() + ",";
                }
            }
        }
        return ids;
    }

    //判断是否还有子级
    public boolean isNotChildren(List<Depart> list, String id) {
        boolean boo = false;
        for (Depart depart : list) {
            if (id.equals(depart.getPid())) {
                boo = true;
                break;
            }
        }
        return boo;
    }

    //删除", notes = "删除【逻辑删除】")
    @PostMapping("/delete/{id}")
    public Result delete(@PathVariable String id) {
        VerifyUtil.notEmpty("数据序号", id);
        Depart depart = new Depart();
        depart.setId(id);
        depart.setIs_delete("1");
        departService.updateById(depart);
        return new ResultUtil().setSuccessMsg(ResultEnums.OK.getReasonPhraseCN());
    }

    //批量删除", notes = "批量删除")
    //(name = "ids", value = "格式:[1,2,3]", dataType = "Array", required = true, paramType = "body")
    @PostMapping("/deleteBatch")
    public Result delete(@RequestBody String[] ids) {
        List<Depart> list = new ArrayList<>();
        for (String id : ids) {
            Depart depart = departService.getById(id);
            if (depart != null) {
                depart.setIs_delete("1");
                list.add(depart);
            }
        }
        if (list.size() > 0) {
            departService.updateBatchById(list);
        }
        return new ResultUtil().setSuccessMsg(ResultEnums.OK.getCode());
    }


    //部门用户树", notes = "部门用户树")
    @GetMapping("getDepartStaffTree")
    public Result<JSONArray> getDepartStaffTree() {
        JSONArray arr = new JSONArray();
        QueryWrapper<Depart> departQuery = new QueryWrapper();
        departQuery.eq("is_delete", "0");
//        departQuery.eq("status", "1");//部门状态:0启用,1禁用
        List<Depart> departs = departService.list(departQuery);
        List<Map<String, String>> wds = departService.findUserDepart();
        String pId = "0";
        loopTree(pId, departs, wds, arr);
        return new ResultUtil().setData(arr);
    }


    public void loopTree(String pId, List<Depart> departs, List<Map<String, String>> wds, JSONArray arr) {
        //判断下方是否还有子级
        if (isNotSub(pId, departs)) {
            for (Depart depart : departs) {
                //添加部门
                if (pId.equals(depart.getPid())) {
                    JSONObject obj1 = new JSONObject();
                    obj1.put("id", depart.getId() + "_0");
                    obj1.put("name", depart.getName());
                    obj1.put("affiliation_enterprise", depart.getAffiliation_enterprise());
                    obj1.put("is_depart", "0");
                    JSONArray arr1 = new JSONArray();
                    for (Map<String, String> wd : wds) {
                        //添加员工
                        if (String.valueOf(wd.get("depart_id")).equals(depart.getId())) {
                            JSONObject obj2 = new JSONObject();
                            obj2.put("id", String.valueOf(wd.get("user_id")) + "_1");
                            obj2.put("name", wd.get("real_name"));
                            obj2.put("is_depart", "1");
                            obj2.put("children", new JSONArray());
                            arr1.add(obj2);
                        }
                    }
                    obj1.put("children", arr1);
                    arr.add(obj1);
                    loopTree(depart.getId(), departs, wds, arr1);
                }
            }
        }
    }

    //是否还有子级
    public boolean isNotSub(String pId, List<Depart> departs) {
        boolean boo = false;
        for (Depart d : departs) {
            if (pId.equals(d.getPid())) {
                boo = true;
                break;
            }
        }
        return boo;
    }

    //部门用户树(全局)", notes = "部门用户树(全局)")
    @GetMapping("/getDepartUserTree")
    public Result<JSONArray> getDepartUserTree() {
        JSONArray arr = new JSONArray();
        QueryWrapper<Depart> departQuery = new QueryWrapper();
        departQuery.eq("is_delete", "0");
        departQuery.eq("status", "1");
        List<Depart> departs = departService.list(departQuery);
        List<Map<String, String>> wds = departService.findUserDepart();
        String pId = "3";
        subTree(pId, departs, wds, arr);
        return new ResultUtil().setData(arr);
    }


    public void subTree(String pId, List<Depart> departs, List<Map<String, String>> wds, JSONArray arr) {
        //判断下方是否还有子级
        if (isNotSub(pId, departs)) {
            for (Depart depart : departs) {
                //添加部门
                if (pId.equals(depart.getPid())) {
                    JSONObject obj1 = new JSONObject();
                    obj1.put("id", depart.getId() + "_1");
                    obj1.put("name", depart.getName());
                    obj1.put("pid", pId);
                    obj1.put("value", depart.getId() + "_" + 1);
                    obj1.put("type", 1);//1代表部门;2代表用户;
                    obj1.put("label", depart.getName());
                    JSONArray arr1 = new JSONArray();
                    for (Map<String, String> wd : wds) {
                        //添加员工
                        if (String.valueOf(wd.get("depart_id")).equals(depart.getId())) {
                            JSONObject obj2 = new JSONObject();
                            obj2.put("id", String.valueOf(wd.get("user_id")) + "_2");
                            obj2.put("name", wd.get("real_name"));
                            obj2.put("pid", "");
                            obj2.put("value", String.valueOf(wd.get("user_id")) + "_2");
                            obj2.put("type", 2);//1代表部门;2代表用户;
                            obj2.put("label", wd.get("real_name"));
                            arr1.add(obj2);
                        }
                    }
                    obj1.put("children", arr1);
                    arr.add(obj1);
                    subTree(depart.getId(), departs, wds, arr1);
                }
            }
        }
    }

    //检测部门", notes = "检测部门")
    @GetMapping("/getDetectiveDepart")
    public Result<List<Depart>> getDetectiveDepart() {
        List<Depart> departTree = departService.getDetectiveDepart();
        return new ResultUtil<List<Depart>>().setData(departTree);
    }


    //部门树", notes = "部门树")
    @GetMapping("/getDepartTree")
    public Result<List<Depart>> getDepartTree(@ModelAttribute Depart depart) {
        List<Depart> departTree = departService.getDepartTree(depart);
        return new ResultUtil<List<Depart>>().setData(departTree);
    }

    //部门子级", notes = "通过父ID获取部门子级")
    @GetMapping("getDepartChildren")
    public Result<List<Depart>> getDepartChildren(@RequestParam(required = false) String pid, @RequestParam(required = false) String name) {
        QueryWrapper<Depart> query = new QueryWrapper();
        query.eq("is_delete", "0");//是否删除
        if (StringUtil.isNotEmpty(name)) {
            query.like("name", name);
        }
        query.orderByAsc("sort");
        List<Depart> list = departService.list(query); //查询所有
        List<Depart> departs = new ArrayList<>();
        //如果不传，默认为父级
        if (!StringUtil.isNotEmpty(pid)) {
            pid = "0";
        }
        for (Depart d : list) {
            if (pid.equals(d.getPid())) {
                //判断是否有子级
                boolean boo = false;
                for (Depart d1 : list) {
                    if (d.getId().equals(d1.getPid())) {
                        boo = true;
                        break;//跳出里面的for循环
                    }
                }
                //供前端使用 无实际意义
                d.setHas_children(boo);
                d.setLeaf(!boo);
                d.setLabel(d.getName());
                d.setAffiliation_enterprise(d.getAffiliation_enterprise());
                departs.add(d);
            }
        }
        return new ResultUtil<List<Depart>>().setData(departs);
    }

    //根据部门id查询所有子部门", notes = "根据部门id查询所有子部门")
    @GetMapping("/getSubDepart")
    public Result<List<Depart>> getSubDepart(@RequestParam(required = true) String id) {
        QueryWrapper<Depart> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("pid", id);
        queryWrapper.eq("is_delete", "0");
        List<Depart> list = departService.list(queryWrapper);
        return new ResultUtil<List<Depart>>().setData(list);
    }

    //找到所有参与合同统计的部门", notes = "找到所有参与合同统计的部门")
    @GetMapping("/getStatisticDepart")
    public Result<List<Depart>> getStatisticDepart() {
        QueryWrapper<Depart> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("is_project_contract_statistic", "1"); //参与合同统计的部门 
        queryWrapper.eq("is_delete", "0");
        List<Depart> list = departService.list(queryWrapper);
        return new ResultUtil<List<Depart>>().setData(list);
    }

    //根据部门名称找到部门信息", notes = "根据部门名称找到部门信息")
    @GetMapping("/findDepartByName")
    public Result<Depart> findDepartByName(String name) {
        QueryWrapper<Depart> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("name", name);
        queryWrapper.eq("is_delete", "0");
        Depart depart = departService.getOne(queryWrapper);
        return new ResultUtil<Depart>().setData(depart);
    }
}
